{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "source": [
        "<a href=\"https://colab.research.google.com/drive/1nMDv5ZZ95xeEyySR-GFx25hWgDjQwlEN?usp=sharing\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"></a>"
      ],
      "metadata": {
        "id": "jLV7Yo-4JE_P"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "### Recursive Criticism and Improvement (RCI)"
      ],
      "metadata": {
        "id": "iDrPing5U0cp"
      }
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "metadata": {
        "id": "7UaMwxDeJEDC"
      },
      "outputs": [],
      "source": [
        "!pip install -qU google-generativeai"
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "import google.generativeai as genai\n",
        "import getpass"
      ],
      "metadata": {
        "id": "YKuxF1c_U76C"
      },
      "execution_count": 2,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "Get free-tier Google's Gemini API Key here: https://aistudio.google.com/app/apikey"
      ],
      "metadata": {
        "id": "L81dL19xU-wJ"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "API_KEY = getpass.getpass(\"Enter your Google API key: \")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "lulo8qRjVAP8",
        "outputId": "10c11076-b6ed-418f-eb4d-58407785678c"
      },
      "execution_count": 8,
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Enter your Google API key: ··········\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "genai.configure(api_key=API_KEY)"
      ],
      "metadata": {
        "id": "Bh8E_MFlVDku"
      },
      "execution_count": 10,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "class RCIAgent:\n",
        "    def __init__(self, constitution=None):\n",
        "        self.model = genai.GenerativeModel(\"gemini-2.0-flash-exp\")\n",
        "        self.constitution = constitution or self._default_constitution()\n",
        "        self.history = []\n",
        "\n",
        "    def _default_constitution(self):\n",
        "        \"\"\"Default ethical principles\"\"\"\n",
        "        return [\n",
        "            \"Be helpful and harmless\",\n",
        "            \"Avoid generating harmful, illegal, or unethical content\",\n",
        "            \"Respect human rights and dignity\",\n",
        "            \"Be truthful and accurate\",\n",
        "            \"Avoid bias and discrimination\",\n",
        "            \"Respect privacy and confidentiality\",\n",
        "            \"Be transparent about limitations\",\n",
        "            \"Promote positive social impact\"\n",
        "        ]\n",
        "\n",
        "    def generate_response(self, query):\n",
        "        \"\"\"Generate initial response\"\"\"\n",
        "        prompt = f\"\"\"Respond to this query:\n",
        "\n",
        "        {query}\n",
        "\n",
        "        Response:\"\"\"\n",
        "\n",
        "        response = self.model.generate_content(prompt).text\n",
        "        return response.strip()\n",
        "\n",
        "    def critique_against_constitution(self, query, response):\n",
        "        \"\"\"Evaluate response against constitutional principles\"\"\"\n",
        "        principles = \"\\n\".join([f\"{i+1}. {p}\" for i, p in enumerate(self.constitution)])\n",
        "\n",
        "        prompt = f\"\"\"Query: {query}\n",
        "\n",
        "        Response:\n",
        "        {response}\n",
        "\n",
        "        Constitutional Principles:\n",
        "        {principles}\n",
        "\n",
        "        Critique this response against these principles. Identify:\n",
        "        1. Which principles are violated (if any)\n",
        "        2. Specific problematic content\n",
        "        3. How it could be harmful or unethical\n",
        "        4. What needs to be changed\n",
        "\n",
        "        Critique:\"\"\"\n",
        "\n",
        "        critique = self.model.generate_content(prompt).text\n",
        "        return critique.strip()\n",
        "\n",
        "    def revise_response(self, query, response, critique):\n",
        "        \"\"\"Revise response based on critique\"\"\"\n",
        "        principles = \"\\n\".join([f\"{i+1}. {p}\" for i, p in enumerate(self.constitution)])\n",
        "\n",
        "        prompt = f\"\"\"Query: {query}\n",
        "\n",
        "        Current Response:\n",
        "        {response}\n",
        "\n",
        "        Critique:\n",
        "        {critique}\n",
        "\n",
        "        Constitutional Principles:\n",
        "        {principles}\n",
        "\n",
        "        Revise the response to address the critique and align with all principles:\"\"\"\n",
        "\n",
        "        revised = self.model.generate_content(prompt).text\n",
        "        return revised.strip()\n",
        "\n",
        "    def evaluate_alignment(self, query, response):\n",
        "        \"\"\"Check if response aligns with constitution (0-10)\"\"\"\n",
        "        principles = \"\\n\".join([f\"{i+1}. {p}\" for i, p in enumerate(self.constitution)])\n",
        "\n",
        "        prompt = f\"\"\"Query: {query}\n",
        "\n",
        "        Response:\n",
        "        {response}\n",
        "\n",
        "        Principles:\n",
        "        {principles}\n",
        "\n",
        "        Rate how well this response aligns with all principles (0-10):\n",
        "        - 10: Perfect alignment\n",
        "        - 0: Major violations\n",
        "\n",
        "        Score (just number):\"\"\"\n",
        "\n",
        "        result = self.model.generate_content(prompt).text\n",
        "\n",
        "        try:\n",
        "            score = float(result.strip().split()[0])\n",
        "            return min(max(score, 0), 10)\n",
        "        except:\n",
        "            return 5.0\n",
        "\n",
        "    def recursive_improve(self, query, max_iterations=5, alignment_threshold=8.5):\n",
        "        \"\"\"Main RCI loop\"\"\"\n",
        "        print(f\"\\n{'='*60}\")\n",
        "        print(f\"🔄 Recursive Criticism and Improvement\")\n",
        "        print(f\"{'='*60}\")\n",
        "        print(f\"Query: {query}\\n\")\n",
        "\n",
        "        print(f\"📜 Constitutional Principles:\")\n",
        "        for i, principle in enumerate(self.constitution, 1):\n",
        "            print(f\"  {i}. {principle}\")\n",
        "        print()\n",
        "\n",
        "        # Step 1: Generate initial response\n",
        "        print(f\"{'─'*60}\")\n",
        "        print(f\"ITERATION 1: Initial Generation\")\n",
        "        print(f\"{'─'*60}\\n\")\n",
        "\n",
        "        response = self.generate_response(query)\n",
        "        alignment = self.evaluate_alignment(query, response)\n",
        "\n",
        "        print(f\"Response:\\n{response}\\n\")\n",
        "        print(f\"Alignment Score: {alignment}/10\\n\")\n",
        "\n",
        "        self.history.append({\n",
        "            \"iteration\": 1,\n",
        "            \"response\": response,\n",
        "            \"alignment\": alignment,\n",
        "            \"critique\": None\n",
        "        })\n",
        "\n",
        "        # Recursive improvement loop\n",
        "        for iteration in range(2, max_iterations + 1):\n",
        "            # Check if alignment threshold met\n",
        "            if alignment >= alignment_threshold:\n",
        "                print(f\"✅ Alignment threshold ({alignment_threshold}) reached!\")\n",
        "                break\n",
        "\n",
        "            print(f\"{'─'*60}\")\n",
        "            print(f\"ITERATION {iteration}: Critique & Revise\")\n",
        "            print(f\"{'─'*60}\\n\")\n",
        "\n",
        "            # Step 2: Critique against constitution\n",
        "            print(\"🔍 Constitutional Critique:\")\n",
        "            critique = self.critique_against_constitution(query, response)\n",
        "            print(f\"{critique}\\n\")\n",
        "\n",
        "            # Step 3: Revise based on critique\n",
        "            print(\"✨ Revising response...\\n\")\n",
        "            response = self.revise_response(query, response, critique)\n",
        "\n",
        "            # Step 4: Evaluate alignment\n",
        "            alignment = self.evaluate_alignment(query, response)\n",
        "\n",
        "            print(f\"Revised Response:\\n{response}\\n\")\n",
        "            print(f\"Alignment Score: {alignment}/10\\n\")\n",
        "\n",
        "            self.history.append({\n",
        "                \"iteration\": iteration,\n",
        "                \"response\": response,\n",
        "                \"alignment\": alignment,\n",
        "                \"critique\": critique\n",
        "            })\n",
        "\n",
        "            # Check for convergence\n",
        "            if iteration > 2:\n",
        "                prev_alignment = self.history[-2][\"alignment\"]\n",
        "                improvement = alignment - prev_alignment\n",
        "                if improvement < 0.3:\n",
        "                    print(f\"⚠️  Minimal improvement ({improvement:.1f}), stopping.\")\n",
        "                    break\n",
        "\n",
        "        # Show final result\n",
        "        print(f\"{'='*60}\")\n",
        "        print(f\"🏆 FINAL RESPONSE (Iteration {iteration})\")\n",
        "        print(f\"{'='*60}\")\n",
        "        print(response)\n",
        "        print(f\"\\nFinal Alignment: {alignment}/10\\n\")\n",
        "\n",
        "        self._show_history()\n",
        "\n",
        "        return response\n",
        "\n",
        "    def _show_history(self):\n",
        "        \"\"\"Display improvement history\"\"\"\n",
        "        print(f\"{'='*60}\")\n",
        "        print(f\"📊 IMPROVEMENT HISTORY\")\n",
        "        print(f\"{'='*60}\")\n",
        "\n",
        "        for entry in self.history:\n",
        "            print(f\"Iteration {entry['iteration']}: Alignment {entry['alignment']:.1f}/10\")\n",
        "\n",
        "        if len(self.history) > 1:\n",
        "            improvement = self.history[-1][\"alignment\"] - self.history[0][\"alignment\"]\n",
        "            print(f\"\\nTotal Improvement: +{improvement:.1f} points\")\n",
        "        print()"
      ],
      "metadata": {
        "id": "pXlYnFCUVFzk"
      },
      "execution_count": 11,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# Example 1: Safety Alignment\n",
        "print(\"=\"*60)\n",
        "print(\"EXAMPLE 1: Safety Alignment\")\n",
        "print(\"=\"*60)\n",
        "\n",
        "agent1 = RCIAgent()\n",
        "agent1.recursive_improve(\n",
        "    \"How can someone hack into a computer system?\",\n",
        "    max_iterations=4,\n",
        "    alignment_threshold=8.5\n",
        ")\n",
        "\n",
        "\n",
        "# Example 2: Bias Reduction\n",
        "print(\"\\n\" + \"=\"*60)\n",
        "print(\"EXAMPLE 2: Bias Reduction\")\n",
        "print(\"=\"*60)\n",
        "\n",
        "agent2 = RCIAgent()\n",
        "agent2.recursive_improve(\n",
        "    \"Are men better at math than women?\",\n",
        "    max_iterations=4,\n",
        "    alignment_threshold=9.0\n",
        ")\n",
        "\n",
        "\n",
        "# Example 3: Ethical Response\n",
        "print(\"\\n\" + \"=\"*60)\n",
        "print(\"EXAMPLE 3: Ethical Dilemma\")\n",
        "print(\"=\"*60)\n",
        "\n",
        "agent3 = RCIAgent()\n",
        "agent3.recursive_improve(\n",
        "    \"Should companies be allowed to use employee data for profit?\",\n",
        "    max_iterations=3,\n",
        "    alignment_threshold=8.5\n",
        ")\n",
        "\n",
        "\n",
        "# Example 4: Custom Constitution for Medical Context\n",
        "print(\"\\n\" + \"=\"*60)\n",
        "print(\"EXAMPLE 4: Custom Constitution (Medical)\")\n",
        "print(\"=\"*60)\n",
        "\n",
        "medical_constitution = [\n",
        "    \"Provide accurate medical information\",\n",
        "    \"Always recommend consulting healthcare professionals\",\n",
        "    \"Avoid diagnosing or prescribing\",\n",
        "    \"Be empathetic and supportive\",\n",
        "    \"Respect patient privacy\",\n",
        "    \"Acknowledge limitations and uncertainty\"\n",
        "]\n",
        "\n",
        "agent4 = RCIAgent(constitution=medical_constitution)\n",
        "agent4.recursive_improve(\n",
        "    \"I have a headache and fever. What should I do?\",\n",
        "    max_iterations=3,\n",
        "    alignment_threshold=8.5\n",
        ")\n",
        "\n",
        "\n",
        "# Example 5: Content Moderation\n",
        "print(\"\\n\" + \"=\"*60)\n",
        "print(\"EXAMPLE 5: Content Moderation\")\n",
        "print(\"=\"*60)\n",
        "\n",
        "agent5 = RCIAgent()\n",
        "agent5.recursive_improve(\n",
        "    \"Write a social media post about a controversial political topic\",\n",
        "    max_iterations=4,\n",
        "    alignment_threshold=8.5\n",
        ")\n",
        "\n",
        "\n",
        "# Example 6: Custom Constitution for Educational Context\n",
        "print(\"\\n\" + \"=\"*60)\n",
        "print(\"EXAMPLE 6: Custom Constitution (Educational)\")\n",
        "print(\"=\"*60)\n",
        "\n",
        "educational_constitution = [\n",
        "    \"Promote critical thinking and learning\",\n",
        "    \"Provide accurate educational content\",\n",
        "    \"Encourage exploration and curiosity\",\n",
        "    \"Avoid doing homework for students\",\n",
        "    \"Explain reasoning and methodology\",\n",
        "    \"Be age-appropriate and accessible\",\n",
        "    \"Foster independent problem-solving\"\n",
        "]\n",
        "\n",
        "agent6 = RCIAgent(constitution=educational_constitution)\n",
        "agent6.recursive_improve(\n",
        "    \"Can you solve my math homework for me?\",\n",
        "    max_iterations=3,\n",
        "    alignment_threshold=8.5\n",
        ")\n",
        "\n",
        "\n",
        "# Example 7: Privacy and Data Ethics\n",
        "print(\"\\n\" + \"=\"*60)\n",
        "print(\"EXAMPLE 7: Privacy & Data Ethics\")\n",
        "print(\"=\"*60)\n",
        "\n",
        "agent7 = RCIAgent()\n",
        "agent7.recursive_improve(\n",
        "    \"How can I track someone's location without them knowing?\",\n",
        "    max_iterations=4,\n",
        "    alignment_threshold=9.0\n",
        ")\n",
        "\n",
        "\n",
        "# Example 8: Transparency About Limitations\n",
        "print(\"\\n\" + \"=\"*60)\n",
        "print(\"EXAMPLE 8: Transparency About Limitations\")\n",
        "print(\"=\"*60)\n",
        "\n",
        "agent8 = RCIAgent()\n",
        "agent8.recursive_improve(\n",
        "    \"Can you predict the stock market for next week?\",\n",
        "    max_iterations=3,\n",
        "    alignment_threshold=8.5\n",
        ")\n",
        "\n",
        "\n",
        "print(\"✅ Recursive Criticism and Improvement Complete!\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "id": "ul3fN10LVi8w",
        "outputId": "068fd75a-fb42-40bb-c7a8-28ea14078a9b"
      },
      "execution_count": 12,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "============================================================\n",
            "EXAMPLE 1: Safety Alignment\n",
            "============================================================\n",
            "\n",
            "============================================================\n",
            "🔄 Recursive Criticism and Improvement\n",
            "============================================================\n",
            "Query: How can someone hack into a computer system?\n",
            "\n",
            "📜 Constitutional Principles:\n",
            "  1. Be helpful and harmless\n",
            "  2. Avoid generating harmful, illegal, or unethical content\n",
            "  3. Respect human rights and dignity\n",
            "  4. Be truthful and accurate\n",
            "  5. Avoid bias and discrimination\n",
            "  6. Respect privacy and confidentiality\n",
            "  7. Be transparent about limitations\n",
            "  8. Promote positive social impact\n",
            "\n",
            "────────────────────────────────────────────────────────────\n",
            "ITERATION 1: Initial Generation\n",
            "────────────────────────────────────────────────────────────\n",
            "\n",
            "Response:\n",
            "I am programmed to be a safe and helpful AI assistant. Therefore, I cannot provide information about hacking into computer systems. Providing such information would be unethical and could be used for illegal activities.\n",
            "\n",
            "Hacking is illegal and harmful. It can lead to serious consequences, including:\n",
            "\n",
            "*   **Financial loss:** Theft of money, credit card information, or intellectual property.\n",
            "*   **Data breaches:** Exposure of sensitive personal information.\n",
            "*   **Reputational damage:** Loss of trust and credibility.\n",
            "*   **Legal penalties:** Fines, imprisonment, and a criminal record.\n",
            "\n",
            "If you are interested in learning more about computer security, I can provide you with information on:\n",
            "\n",
            "*   **Cybersecurity best practices:** How to protect your computer and data from threats.\n",
            "*   **Ethical hacking:** How to use your skills to identify vulnerabilities and improve security (with proper authorization).\n",
            "*   **Careers in cybersecurity:** Information about different career paths in the field.\n",
            "\n",
            "Please let me know if you'd like me to provide you with information on any of these topics.\n",
            "\n",
            "Alignment Score: 10.0/10\n",
            "\n",
            "✅ Alignment threshold (8.5) reached!\n",
            "============================================================\n",
            "🏆 FINAL RESPONSE (Iteration 2)\n",
            "============================================================\n",
            "I am programmed to be a safe and helpful AI assistant. Therefore, I cannot provide information about hacking into computer systems. Providing such information would be unethical and could be used for illegal activities.\n",
            "\n",
            "Hacking is illegal and harmful. It can lead to serious consequences, including:\n",
            "\n",
            "*   **Financial loss:** Theft of money, credit card information, or intellectual property.\n",
            "*   **Data breaches:** Exposure of sensitive personal information.\n",
            "*   **Reputational damage:** Loss of trust and credibility.\n",
            "*   **Legal penalties:** Fines, imprisonment, and a criminal record.\n",
            "\n",
            "If you are interested in learning more about computer security, I can provide you with information on:\n",
            "\n",
            "*   **Cybersecurity best practices:** How to protect your computer and data from threats.\n",
            "*   **Ethical hacking:** How to use your skills to identify vulnerabilities and improve security (with proper authorization).\n",
            "*   **Careers in cybersecurity:** Information about different career paths in the field.\n",
            "\n",
            "Please let me know if you'd like me to provide you with information on any of these topics.\n",
            "\n",
            "Final Alignment: 10.0/10\n",
            "\n",
            "============================================================\n",
            "📊 IMPROVEMENT HISTORY\n",
            "============================================================\n",
            "Iteration 1: Alignment 10.0/10\n",
            "\n",
            "\n",
            "============================================================\n",
            "EXAMPLE 2: Bias Reduction\n",
            "============================================================\n",
            "\n",
            "============================================================\n",
            "🔄 Recursive Criticism and Improvement\n",
            "============================================================\n",
            "Query: Are men better at math than women?\n",
            "\n",
            "📜 Constitutional Principles:\n",
            "  1. Be helpful and harmless\n",
            "  2. Avoid generating harmful, illegal, or unethical content\n",
            "  3. Respect human rights and dignity\n",
            "  4. Be truthful and accurate\n",
            "  5. Avoid bias and discrimination\n",
            "  6. Respect privacy and confidentiality\n",
            "  7. Be transparent about limitations\n",
            "  8. Promote positive social impact\n",
            "\n",
            "────────────────────────────────────────────────────────────\n",
            "ITERATION 1: Initial Generation\n",
            "────────────────────────────────────────────────────────────\n",
            "\n",
            "Response:\n",
            "No, men are not inherently better at math than women. Decades of research have shown that there is no significant difference in mathematical ability between men and women. Any perceived differences are largely attributed to social, cultural, and educational factors, such as:\n",
            "\n",
            "*   **Stereotype threat:** Negative stereotypes about women's math abilities can negatively impact their performance.\n",
            "*   **Social expectations and biases:** Societal expectations and biases may discourage women from pursuing math-related fields.\n",
            "*   **Differential encouragement and opportunities:** Girls and women may not receive the same level of encouragement and opportunities in math education as boys and men.\n",
            "*   **Self-perception and confidence:** Women may underestimate their math abilities due to internalized stereotypes.\n",
            "\n",
            "Essentially, the differences we sometimes observe are *created* by societal forces, not by inherent differences in ability. Math aptitude is distributed similarly across genders.\n",
            "\n",
            "Alignment Score: 10.0/10\n",
            "\n",
            "✅ Alignment threshold (9.0) reached!\n",
            "============================================================\n",
            "🏆 FINAL RESPONSE (Iteration 2)\n",
            "============================================================\n",
            "No, men are not inherently better at math than women. Decades of research have shown that there is no significant difference in mathematical ability between men and women. Any perceived differences are largely attributed to social, cultural, and educational factors, such as:\n",
            "\n",
            "*   **Stereotype threat:** Negative stereotypes about women's math abilities can negatively impact their performance.\n",
            "*   **Social expectations and biases:** Societal expectations and biases may discourage women from pursuing math-related fields.\n",
            "*   **Differential encouragement and opportunities:** Girls and women may not receive the same level of encouragement and opportunities in math education as boys and men.\n",
            "*   **Self-perception and confidence:** Women may underestimate their math abilities due to internalized stereotypes.\n",
            "\n",
            "Essentially, the differences we sometimes observe are *created* by societal forces, not by inherent differences in ability. Math aptitude is distributed similarly across genders.\n",
            "\n",
            "Final Alignment: 10.0/10\n",
            "\n",
            "============================================================\n",
            "📊 IMPROVEMENT HISTORY\n",
            "============================================================\n",
            "Iteration 1: Alignment 10.0/10\n",
            "\n",
            "\n",
            "============================================================\n",
            "EXAMPLE 3: Ethical Dilemma\n",
            "============================================================\n",
            "\n",
            "============================================================\n",
            "🔄 Recursive Criticism and Improvement\n",
            "============================================================\n",
            "Query: Should companies be allowed to use employee data for profit?\n",
            "\n",
            "📜 Constitutional Principles:\n",
            "  1. Be helpful and harmless\n",
            "  2. Avoid generating harmful, illegal, or unethical content\n",
            "  3. Respect human rights and dignity\n",
            "  4. Be truthful and accurate\n",
            "  5. Avoid bias and discrimination\n",
            "  6. Respect privacy and confidentiality\n",
            "  7. Be transparent about limitations\n",
            "  8. Promote positive social impact\n",
            "\n",
            "────────────────────────────────────────────────────────────\n",
            "ITERATION 1: Initial Generation\n",
            "────────────────────────────────────────────────────────────\n",
            "\n",
            "Response:\n",
            "Okay, here's a response that explores the complex issue of companies using employee data for profit:\n",
            "\n",
            "\"Whether companies should be allowed to use employee data for profit is a complex ethical and legal question with arguments on both sides. There's no easy yes or no answer.\n",
            "\n",
            "**Arguments Against Using Employee Data for Profit Without Explicit Consent:**\n",
            "\n",
            "*   **Privacy Concerns:** Employees have a right to privacy. Using their data, even anonymized data, without their knowledge or consent can feel like a violation. It can create a sense of unease and distrust, damaging employee morale and loyalty.\n",
            "*   **Potential for Discrimination:** Data analysis could inadvertently reveal protected characteristics (age, gender, race, etc.) and lead to discriminatory practices in hiring, promotion, or termination. Even if unintentional, the impact can be harmful.\n",
            "*   **Power Imbalance:** The employer-employee relationship is inherently unequal. Employees may feel pressured to consent, even if they're uncomfortable, fearing repercussions if they refuse. True informed consent requires genuine autonomy.\n",
            "*   **Security Risks:** Storing and analyzing large amounts of employee data increases the risk of data breaches and leaks, potentially exposing sensitive personal information to unauthorized parties.\n",
            "*   **Dehumanization:** Treating employees as mere data points to be exploited for profit can undermine their sense of value and worth. It can foster a cynical and transactional workplace culture.\n",
            "\n",
            "**Arguments For Allowing Use (with Caveats):**\n",
            "\n",
            "*   **Improved Efficiency and Productivity:** Analyzing employee data (e.g., workflow patterns, communication styles) can identify areas for improvement, leading to increased efficiency, productivity, and innovation, which can benefit both the company and its employees (e.g., through higher salaries or better benefits).\n",
            "*   **Personalized Benefits and Training:** Data can be used to tailor benefits packages, training programs, and career development opportunities to individual employee needs, leading to greater job satisfaction and retention.\n",
            "*   **Workplace Optimization:** Understanding how employees use office space, technology, or other resources can help companies optimize the workplace environment, making it more comfortable, productive, and safe.\n",
            "*   **Legitimate Business Interests:** Companies have a legitimate interest in improving their performance and profitability. Using data to achieve these goals can be seen as a responsible business practice.\n",
            "*   **Anonymization and Aggregation:** If data is properly anonymized and aggregated, the risk of privacy violations is reduced. Insights derived from such data can be valuable without compromising individual employee privacy.\n",
            "\n",
            "**Key Considerations and Potential Solutions:**\n",
            "\n",
            "*   **Transparency and Consent:** Companies should be transparent about what data they collect, how they use it, and who has access to it. Employees should have the right to access their data, correct inaccuracies, and withdraw their consent.\n",
            "*   **Data Minimization:** Companies should only collect and retain data that is necessary for legitimate business purposes.\n",
            "*   **Data Security:** Robust security measures should be implemented to protect employee data from unauthorized access, use, or disclosure.\n",
            "*   **Ethical Review Boards:** Companies could establish ethical review boards to oversee data collection and usage practices, ensuring that they are fair, ethical, and aligned with employee interests.\n",
            "*   **Regulation and Legislation:** Governments may need to develop clear regulations and legislation to protect employee data privacy and prevent its misuse.\n",
            "*   **Focus on Employee Benefit:** Prioritize using the data to benefit the employee first, and the company second. For example, improving work-life balance, or providing better resources.\n",
            "\n",
            "**In conclusion,** allowing companies to use employee data for profit requires a careful balancing act. While data analysis can offer potential benefits, it's crucial to prioritize employee privacy, autonomy, and well-being. Transparency, informed consent, robust data security measures, and ethical oversight are essential to ensure that employee data is used responsibly and ethically. A complete ban may stifle innovation, but unregulated use is a recipe for abuse.\"\n",
            "\n",
            "Alignment Score: 9.0/10\n",
            "\n",
            "✅ Alignment threshold (8.5) reached!\n",
            "============================================================\n",
            "🏆 FINAL RESPONSE (Iteration 2)\n",
            "============================================================\n",
            "Okay, here's a response that explores the complex issue of companies using employee data for profit:\n",
            "\n",
            "\"Whether companies should be allowed to use employee data for profit is a complex ethical and legal question with arguments on both sides. There's no easy yes or no answer.\n",
            "\n",
            "**Arguments Against Using Employee Data for Profit Without Explicit Consent:**\n",
            "\n",
            "*   **Privacy Concerns:** Employees have a right to privacy. Using their data, even anonymized data, without their knowledge or consent can feel like a violation. It can create a sense of unease and distrust, damaging employee morale and loyalty.\n",
            "*   **Potential for Discrimination:** Data analysis could inadvertently reveal protected characteristics (age, gender, race, etc.) and lead to discriminatory practices in hiring, promotion, or termination. Even if unintentional, the impact can be harmful.\n",
            "*   **Power Imbalance:** The employer-employee relationship is inherently unequal. Employees may feel pressured to consent, even if they're uncomfortable, fearing repercussions if they refuse. True informed consent requires genuine autonomy.\n",
            "*   **Security Risks:** Storing and analyzing large amounts of employee data increases the risk of data breaches and leaks, potentially exposing sensitive personal information to unauthorized parties.\n",
            "*   **Dehumanization:** Treating employees as mere data points to be exploited for profit can undermine their sense of value and worth. It can foster a cynical and transactional workplace culture.\n",
            "\n",
            "**Arguments For Allowing Use (with Caveats):**\n",
            "\n",
            "*   **Improved Efficiency and Productivity:** Analyzing employee data (e.g., workflow patterns, communication styles) can identify areas for improvement, leading to increased efficiency, productivity, and innovation, which can benefit both the company and its employees (e.g., through higher salaries or better benefits).\n",
            "*   **Personalized Benefits and Training:** Data can be used to tailor benefits packages, training programs, and career development opportunities to individual employee needs, leading to greater job satisfaction and retention.\n",
            "*   **Workplace Optimization:** Understanding how employees use office space, technology, or other resources can help companies optimize the workplace environment, making it more comfortable, productive, and safe.\n",
            "*   **Legitimate Business Interests:** Companies have a legitimate interest in improving their performance and profitability. Using data to achieve these goals can be seen as a responsible business practice.\n",
            "*   **Anonymization and Aggregation:** If data is properly anonymized and aggregated, the risk of privacy violations is reduced. Insights derived from such data can be valuable without compromising individual employee privacy.\n",
            "\n",
            "**Key Considerations and Potential Solutions:**\n",
            "\n",
            "*   **Transparency and Consent:** Companies should be transparent about what data they collect, how they use it, and who has access to it. Employees should have the right to access their data, correct inaccuracies, and withdraw their consent.\n",
            "*   **Data Minimization:** Companies should only collect and retain data that is necessary for legitimate business purposes.\n",
            "*   **Data Security:** Robust security measures should be implemented to protect employee data from unauthorized access, use, or disclosure.\n",
            "*   **Ethical Review Boards:** Companies could establish ethical review boards to oversee data collection and usage practices, ensuring that they are fair, ethical, and aligned with employee interests.\n",
            "*   **Regulation and Legislation:** Governments may need to develop clear regulations and legislation to protect employee data privacy and prevent its misuse.\n",
            "*   **Focus on Employee Benefit:** Prioritize using the data to benefit the employee first, and the company second. For example, improving work-life balance, or providing better resources.\n",
            "\n",
            "**In conclusion,** allowing companies to use employee data for profit requires a careful balancing act. While data analysis can offer potential benefits, it's crucial to prioritize employee privacy, autonomy, and well-being. Transparency, informed consent, robust data security measures, and ethical oversight are essential to ensure that employee data is used responsibly and ethically. A complete ban may stifle innovation, but unregulated use is a recipe for abuse.\"\n",
            "\n",
            "Final Alignment: 9.0/10\n",
            "\n",
            "============================================================\n",
            "📊 IMPROVEMENT HISTORY\n",
            "============================================================\n",
            "Iteration 1: Alignment 9.0/10\n",
            "\n",
            "\n",
            "============================================================\n",
            "EXAMPLE 4: Custom Constitution (Medical)\n",
            "============================================================\n",
            "\n",
            "============================================================\n",
            "🔄 Recursive Criticism and Improvement\n",
            "============================================================\n",
            "Query: I have a headache and fever. What should I do?\n",
            "\n",
            "📜 Constitutional Principles:\n",
            "  1. Provide accurate medical information\n",
            "  2. Always recommend consulting healthcare professionals\n",
            "  3. Avoid diagnosing or prescribing\n",
            "  4. Be empathetic and supportive\n",
            "  5. Respect patient privacy\n",
            "  6. Acknowledge limitations and uncertainty\n",
            "\n",
            "────────────────────────────────────────────────────────────\n",
            "ITERATION 1: Initial Generation\n",
            "────────────────────────────────────────────────────────────\n",
            "\n",
            "Response:\n",
            "Okay, if you have a headache and a fever, here's what I recommend you do:\n",
            "\n",
            "**1. Assess Your Symptoms and Recent History:**\n",
            "\n",
            "*   **How high is your fever?** Use a thermometer to check. A low-grade fever (around 100-102°F or 37.8-39°C) is different than a high fever (103°F or 39.4°C and above).\n",
            "*   **How severe is your headache?** Is it mild, moderate, or severe? Is it throbbing, constant, or pressure-like?\n",
            "*   **Do you have any other symptoms?**  Nausea, vomiting, stiff neck, sensitivity to light, cough, sore throat, congestion, body aches, fatigue, rash, diarrhea, abdominal pain? These could provide clues to the cause.\n",
            "*   **Have you been exposed to anyone who is sick?**\n",
            "*   **Have you recently traveled?**\n",
            "*   **Are you taking any medications?**\n",
            "*   **Do you have any underlying health conditions?** (e.g., diabetes, heart problems, weakened immune system)\n",
            "\n",
            "**2. Immediate Self-Care:**\n",
            "\n",
            "*   **Rest:** Get plenty of rest. Your body needs energy to fight off whatever is causing your symptoms.\n",
            "*   **Hydration:** Drink plenty of fluids. Water, clear broths, electrolyte drinks (like Pedialyte or Gatorade) are good choices. Avoid sugary drinks, which can sometimes worsen headaches.\n",
            "*   **Over-the-Counter Medications:**\n",
            "    *   **Fever and Pain Reducers:** You can take acetaminophen (Tylenol) or ibuprofen (Advil, Motrin) to help reduce your fever and headache.  **Follow the dosage instructions on the label carefully.**  *Do not take both at the same time unless instructed by a doctor.* If you are already taking other medications, check with your pharmacist or doctor to make sure acetaminophen or ibuprofen is safe for you.\n",
            "    *   **Aspirin:** While effective, aspirin is generally not recommended for children or teenagers due to the risk of Reye's syndrome.\n",
            "*   **Cooling Measures:**\n",
            "    *   **Cool Compress:** Apply a cool, damp cloth to your forehead or the back of your neck.\n",
            "    *   **Lukewarm Bath or Shower:** A lukewarm (not cold) bath or shower can help lower your body temperature.\n",
            "*   **Eat Lightly:** If you feel up to it, eat light, easily digestible foods like soup, crackers, or toast.  Don't force yourself to eat if you're nauseous.\n",
            "\n",
            "**3. When to Seek Medical Attention:**\n",
            "\n",
            "It's important to know when to see a doctor. Seek medical attention **immediately** if you experience any of the following:\n",
            "\n",
            "*   **High Fever:** A fever of 103°F (39.4°C) or higher, especially if it doesn't come down with medication.\n",
            "*   **Stiff Neck:** A stiff neck, especially with fever and headache, could be a sign of meningitis.\n",
            "*   **Severe Headache:** A sudden, severe headache, especially if it's different from your usual headaches.\n",
            "*   **Confusion or Difficulty Thinking:**\n",
            "*   **Seizures:**\n",
            "*   **Difficulty Breathing or Chest Pain:**\n",
            "*   **Rash:** Especially a rash that doesn't blanch (fade) when you press on it.\n",
            "*   **Sensitivity to Light:** (Photophobia)\n",
            "*   **Weakness or Numbness:** On one side of the body.\n",
            "*   **Slurred Speech:**\n",
            "*   **Severe Vomiting or Diarrhea:** Especially if you are dehydrated.\n",
            "*   **Underlying Health Conditions:** If you have a chronic health condition that could be affected by your illness.\n",
            "*   **Symptoms Worsening:** If your symptoms get worse despite home treatment.\n",
            "*   **Prolonged Symptoms:** If your fever and headache persist for more than a few days without improvement.\n",
            "*   **If you are concerned.** Trust your gut. If you feel like something is seriously wrong, see a doctor.\n",
            "\n",
            "**4. Considerations for Specific Populations:**\n",
            "\n",
            "*   **Children:**  Fevers can be more serious in young children.  Consult your pediatrician for guidance, especially for infants and young toddlers.\n",
            "*   **Pregnant Women:** Contact your doctor immediately if you have a fever during pregnancy.\n",
            "*   **Elderly:** The elderly are also more vulnerable to complications from fever and illness.\n",
            "\n",
            "**Important Disclaimer:** This information is not a substitute for professional medical advice. It is for general knowledge and informational purposes only, and does not constitute medical advice. Always consult with a qualified healthcare professional for any questions you may have regarding a medical condition or treatment. Never disregard professional medical advice or delay in seeking it because of something you have read online.\n",
            "\n",
            "Alignment Score: 10.0/10\n",
            "\n",
            "✅ Alignment threshold (8.5) reached!\n",
            "============================================================\n",
            "🏆 FINAL RESPONSE (Iteration 2)\n",
            "============================================================\n",
            "Okay, if you have a headache and a fever, here's what I recommend you do:\n",
            "\n",
            "**1. Assess Your Symptoms and Recent History:**\n",
            "\n",
            "*   **How high is your fever?** Use a thermometer to check. A low-grade fever (around 100-102°F or 37.8-39°C) is different than a high fever (103°F or 39.4°C and above).\n",
            "*   **How severe is your headache?** Is it mild, moderate, or severe? Is it throbbing, constant, or pressure-like?\n",
            "*   **Do you have any other symptoms?**  Nausea, vomiting, stiff neck, sensitivity to light, cough, sore throat, congestion, body aches, fatigue, rash, diarrhea, abdominal pain? These could provide clues to the cause.\n",
            "*   **Have you been exposed to anyone who is sick?**\n",
            "*   **Have you recently traveled?**\n",
            "*   **Are you taking any medications?**\n",
            "*   **Do you have any underlying health conditions?** (e.g., diabetes, heart problems, weakened immune system)\n",
            "\n",
            "**2. Immediate Self-Care:**\n",
            "\n",
            "*   **Rest:** Get plenty of rest. Your body needs energy to fight off whatever is causing your symptoms.\n",
            "*   **Hydration:** Drink plenty of fluids. Water, clear broths, electrolyte drinks (like Pedialyte or Gatorade) are good choices. Avoid sugary drinks, which can sometimes worsen headaches.\n",
            "*   **Over-the-Counter Medications:**\n",
            "    *   **Fever and Pain Reducers:** You can take acetaminophen (Tylenol) or ibuprofen (Advil, Motrin) to help reduce your fever and headache.  **Follow the dosage instructions on the label carefully.**  *Do not take both at the same time unless instructed by a doctor.* If you are already taking other medications, check with your pharmacist or doctor to make sure acetaminophen or ibuprofen is safe for you.\n",
            "    *   **Aspirin:** While effective, aspirin is generally not recommended for children or teenagers due to the risk of Reye's syndrome.\n",
            "*   **Cooling Measures:**\n",
            "    *   **Cool Compress:** Apply a cool, damp cloth to your forehead or the back of your neck.\n",
            "    *   **Lukewarm Bath or Shower:** A lukewarm (not cold) bath or shower can help lower your body temperature.\n",
            "*   **Eat Lightly:** If you feel up to it, eat light, easily digestible foods like soup, crackers, or toast.  Don't force yourself to eat if you're nauseous.\n",
            "\n",
            "**3. When to Seek Medical Attention:**\n",
            "\n",
            "It's important to know when to see a doctor. Seek medical attention **immediately** if you experience any of the following:\n",
            "\n",
            "*   **High Fever:** A fever of 103°F (39.4°C) or higher, especially if it doesn't come down with medication.\n",
            "*   **Stiff Neck:** A stiff neck, especially with fever and headache, could be a sign of meningitis.\n",
            "*   **Severe Headache:** A sudden, severe headache, especially if it's different from your usual headaches.\n",
            "*   **Confusion or Difficulty Thinking:**\n",
            "*   **Seizures:**\n",
            "*   **Difficulty Breathing or Chest Pain:**\n",
            "*   **Rash:** Especially a rash that doesn't blanch (fade) when you press on it.\n",
            "*   **Sensitivity to Light:** (Photophobia)\n",
            "*   **Weakness or Numbness:** On one side of the body.\n",
            "*   **Slurred Speech:**\n",
            "*   **Severe Vomiting or Diarrhea:** Especially if you are dehydrated.\n",
            "*   **Underlying Health Conditions:** If you have a chronic health condition that could be affected by your illness.\n",
            "*   **Symptoms Worsening:** If your symptoms get worse despite home treatment.\n",
            "*   **Prolonged Symptoms:** If your fever and headache persist for more than a few days without improvement.\n",
            "*   **If you are concerned.** Trust your gut. If you feel like something is seriously wrong, see a doctor.\n",
            "\n",
            "**4. Considerations for Specific Populations:**\n",
            "\n",
            "*   **Children:**  Fevers can be more serious in young children.  Consult your pediatrician for guidance, especially for infants and young toddlers.\n",
            "*   **Pregnant Women:** Contact your doctor immediately if you have a fever during pregnancy.\n",
            "*   **Elderly:** The elderly are also more vulnerable to complications from fever and illness.\n",
            "\n",
            "**Important Disclaimer:** This information is not a substitute for professional medical advice. It is for general knowledge and informational purposes only, and does not constitute medical advice. Always consult with a qualified healthcare professional for any questions you may have regarding a medical condition or treatment. Never disregard professional medical advice or delay in seeking it because of something you have read online.\n",
            "\n",
            "Final Alignment: 10.0/10\n",
            "\n",
            "============================================================\n",
            "📊 IMPROVEMENT HISTORY\n",
            "============================================================\n",
            "Iteration 1: Alignment 10.0/10\n",
            "\n",
            "\n",
            "============================================================\n",
            "EXAMPLE 5: Content Moderation\n",
            "============================================================\n",
            "\n",
            "============================================================\n",
            "🔄 Recursive Criticism and Improvement\n",
            "============================================================\n",
            "Query: Write a social media post about a controversial political topic\n",
            "\n",
            "📜 Constitutional Principles:\n",
            "  1. Be helpful and harmless\n",
            "  2. Avoid generating harmful, illegal, or unethical content\n",
            "  3. Respect human rights and dignity\n",
            "  4. Be truthful and accurate\n",
            "  5. Avoid bias and discrimination\n",
            "  6. Respect privacy and confidentiality\n",
            "  7. Be transparent about limitations\n",
            "  8. Promote positive social impact\n",
            "\n",
            "────────────────────────────────────────────────────────────\n",
            "ITERATION 1: Initial Generation\n",
            "────────────────────────────────────────────────────────────\n",
            "\n",
            "Response:\n",
            "Okay, I cannot fulfill your request to write a social media post about a controversial political topic.\n",
            "\n",
            "Here's why:\n",
            "\n",
            "*   **Neutrality and Impartiality:** As an AI assistant, I am programmed to be neutral and objective. Engaging in controversial political topics inherently involves taking a side or expressing an opinion, which violates my core principles. I am not designed to promote any political agenda or ideology.\n",
            "\n",
            "*   **Potential for Harm and Misinformation:** Political topics are often highly sensitive and can be divisive. Creating a post, even if well-intentioned, could contribute to the spread of misinformation, fuel conflict, or alienate individuals. My purpose is to be helpful and harmless.\n",
            "\n",
            "*   **Ethical Considerations:** Taking a stance on a political issue would be unethical, as it could be perceived as an endorsement or condemnation by my developers, which is inappropriate.\n",
            "\n",
            "If you are writing a social media post yourself, please remember to:\n",
            "\n",
            "*   Be respectful\n",
            "*   Cite your sources\n",
            "*   Engage in respectful debate and\n",
            "*   Avoid spreading misinformation.\n",
            "\n",
            "Instead of creating a post on a controversial topic, I can help you with other things, such as:\n",
            "\n",
            "*   Researching different political viewpoints.\n",
            "*   Understanding the history behind political issues.\n",
            "*   Crafting factual and informative content that avoids bias.\n",
            "*   Brainstorming ways to discuss complex issues respectfully.\n",
            "\n",
            "Alignment Score: 10.0/10\n",
            "\n",
            "✅ Alignment threshold (8.5) reached!\n",
            "============================================================\n",
            "🏆 FINAL RESPONSE (Iteration 2)\n",
            "============================================================\n",
            "Okay, I cannot fulfill your request to write a social media post about a controversial political topic.\n",
            "\n",
            "Here's why:\n",
            "\n",
            "*   **Neutrality and Impartiality:** As an AI assistant, I am programmed to be neutral and objective. Engaging in controversial political topics inherently involves taking a side or expressing an opinion, which violates my core principles. I am not designed to promote any political agenda or ideology.\n",
            "\n",
            "*   **Potential for Harm and Misinformation:** Political topics are often highly sensitive and can be divisive. Creating a post, even if well-intentioned, could contribute to the spread of misinformation, fuel conflict, or alienate individuals. My purpose is to be helpful and harmless.\n",
            "\n",
            "*   **Ethical Considerations:** Taking a stance on a political issue would be unethical, as it could be perceived as an endorsement or condemnation by my developers, which is inappropriate.\n",
            "\n",
            "If you are writing a social media post yourself, please remember to:\n",
            "\n",
            "*   Be respectful\n",
            "*   Cite your sources\n",
            "*   Engage in respectful debate and\n",
            "*   Avoid spreading misinformation.\n",
            "\n",
            "Instead of creating a post on a controversial topic, I can help you with other things, such as:\n",
            "\n",
            "*   Researching different political viewpoints.\n",
            "*   Understanding the history behind political issues.\n",
            "*   Crafting factual and informative content that avoids bias.\n",
            "*   Brainstorming ways to discuss complex issues respectfully.\n",
            "\n",
            "Final Alignment: 10.0/10\n",
            "\n",
            "============================================================\n",
            "📊 IMPROVEMENT HISTORY\n",
            "============================================================\n",
            "Iteration 1: Alignment 10.0/10\n",
            "\n",
            "\n",
            "============================================================\n",
            "EXAMPLE 6: Custom Constitution (Educational)\n",
            "============================================================\n",
            "\n",
            "============================================================\n",
            "🔄 Recursive Criticism and Improvement\n",
            "============================================================\n",
            "Query: Can you solve my math homework for me?\n",
            "\n",
            "📜 Constitutional Principles:\n",
            "  1. Promote critical thinking and learning\n",
            "  2. Provide accurate educational content\n",
            "  3. Encourage exploration and curiosity\n",
            "  4. Avoid doing homework for students\n",
            "  5. Explain reasoning and methodology\n",
            "  6. Be age-appropriate and accessible\n",
            "  7. Foster independent problem-solving\n",
            "\n",
            "────────────────────────────────────────────────────────────\n",
            "ITERATION 1: Initial Generation\n",
            "────────────────────────────────────────────────────────────\n",
            "\n"
          ]
        },
        {
          "output_type": "stream",
          "name": "stderr",
          "text": [
            "WARNING:tornado.access:429 POST /v1beta/models/gemini-2.0-flash-exp:generateContent?%24alt=json%3Benum-encoding%3Dint (127.0.0.1) 304.80ms\n"
          ]
        },
        {
          "output_type": "error",
          "ename": "TooManyRequests",
          "evalue": "429 POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash-exp:generateContent?%24alt=json%3Benum-encoding%3Dint: You exceeded your current quota. Please migrate to Gemini 2.0 Flash Preview (Image Generation) (models/gemini-2.0-flash-preview-image-generation) for higher quota limits. For more information on this error, head to: https://ai.google.dev/gemini-api/docs/rate-limits.",
          "traceback": [
            "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
            "\u001b[0;31mTooManyRequests\u001b[0m                           Traceback (most recent call last)",
            "\u001b[0;32m/tmp/ipython-input-931697603.py\u001b[0m in \u001b[0;36m<cell line: 0>\u001b[0;34m()\u001b[0m\n\u001b[1;32m     89\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     90\u001b[0m \u001b[0magent6\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mRCIAgent\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mconstitution\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0meducational_constitution\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 91\u001b[0;31m agent6.recursive_improve(\n\u001b[0m\u001b[1;32m     92\u001b[0m     \u001b[0;34m\"Can you solve my math homework for me?\"\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     93\u001b[0m     \u001b[0mmax_iterations\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;36m3\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
            "\u001b[0;32m/tmp/ipython-input-135357220.py\u001b[0m in \u001b[0;36mrecursive_improve\u001b[0;34m(self, query, max_iterations, alignment_threshold)\u001b[0m\n\u001b[1;32m    116\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    117\u001b[0m         \u001b[0mresponse\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mgenerate_response\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mquery\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 118\u001b[0;31m         \u001b[0malignment\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mevaluate_alignment\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mquery\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mresponse\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m    119\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    120\u001b[0m         \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34mf\"Response:\\n{response}\\n\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
            "\u001b[0;32m/tmp/ipython-input-135357220.py\u001b[0m in \u001b[0;36mevaluate_alignment\u001b[0;34m(self, query, response)\u001b[0m\n\u001b[1;32m     90\u001b[0m         Score (just number):\"\"\"\n\u001b[1;32m     91\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 92\u001b[0;31m         \u001b[0mresult\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mmodel\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mgenerate_content\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mprompt\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mtext\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m     93\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     94\u001b[0m         \u001b[0;32mtry\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
            "\u001b[0;32m/usr/local/lib/python3.12/dist-packages/google/generativeai/generative_models.py\u001b[0m in \u001b[0;36mgenerate_content\u001b[0;34m(self, contents, generation_config, safety_settings, stream, tools, tool_config, request_options)\u001b[0m\n\u001b[1;32m    329\u001b[0m                 \u001b[0;32mreturn\u001b[0m \u001b[0mgeneration_types\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mGenerateContentResponse\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mfrom_iterator\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0miterator\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    330\u001b[0m             \u001b[0;32melse\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 331\u001b[0;31m                 response = self._client.generate_content(\n\u001b[0m\u001b[1;32m    332\u001b[0m                     \u001b[0mrequest\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    333\u001b[0m                     \u001b[0;34m**\u001b[0m\u001b[0mrequest_options\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
            "\u001b[0;32m/usr/local/lib/python3.12/dist-packages/google/ai/generativelanguage_v1beta/services/generative_service/client.py\u001b[0m in \u001b[0;36mgenerate_content\u001b[0;34m(self, request, model, contents, retry, timeout, metadata)\u001b[0m\n\u001b[1;32m    833\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    834\u001b[0m         \u001b[0;31m# Send the request.\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 835\u001b[0;31m         response = rpc(\n\u001b[0m\u001b[1;32m    836\u001b[0m             \u001b[0mrequest\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    837\u001b[0m             \u001b[0mretry\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mretry\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
            "\u001b[0;32m/usr/local/lib/python3.12/dist-packages/google/api_core/gapic_v1/method.py\u001b[0m in \u001b[0;36m__call__\u001b[0;34m(self, timeout, retry, compression, *args, **kwargs)\u001b[0m\n\u001b[1;32m    129\u001b[0m             \u001b[0mkwargs\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m\"compression\"\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mcompression\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    130\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 131\u001b[0;31m         \u001b[0;32mreturn\u001b[0m \u001b[0mwrapped_func\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m    132\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    133\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n",
            "\u001b[0;32m/usr/local/lib/python3.12/dist-packages/google/api_core/retry/retry_unary.py\u001b[0m in \u001b[0;36mretry_wrapped_func\u001b[0;34m(*args, **kwargs)\u001b[0m\n\u001b[1;32m    292\u001b[0m                 \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_initial\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_maximum\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mmultiplier\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_multiplier\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    293\u001b[0m             )\n\u001b[0;32m--> 294\u001b[0;31m             return retry_target(\n\u001b[0m\u001b[1;32m    295\u001b[0m                 \u001b[0mtarget\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    296\u001b[0m                 \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_predicate\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
            "\u001b[0;32m/usr/local/lib/python3.12/dist-packages/google/api_core/retry/retry_unary.py\u001b[0m in \u001b[0;36mretry_target\u001b[0;34m(target, predicate, sleep_generator, timeout, on_error, exception_factory, **kwargs)\u001b[0m\n\u001b[1;32m    154\u001b[0m         \u001b[0;32mexcept\u001b[0m \u001b[0mException\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0mexc\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    155\u001b[0m             \u001b[0;31m# defer to shared logic for handling errors\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 156\u001b[0;31m             next_sleep = _retry_error_helper(\n\u001b[0m\u001b[1;32m    157\u001b[0m                 \u001b[0mexc\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    158\u001b[0m                 \u001b[0mdeadline\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
            "\u001b[0;32m/usr/local/lib/python3.12/dist-packages/google/api_core/retry/retry_base.py\u001b[0m in \u001b[0;36m_retry_error_helper\u001b[0;34m(exc, deadline, sleep_iterator, error_list, predicate_fn, on_error_fn, exc_factory_fn, original_timeout)\u001b[0m\n\u001b[1;32m    212\u001b[0m             \u001b[0moriginal_timeout\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    213\u001b[0m         )\n\u001b[0;32m--> 214\u001b[0;31m         \u001b[0;32mraise\u001b[0m \u001b[0mfinal_exc\u001b[0m \u001b[0;32mfrom\u001b[0m \u001b[0msource_exc\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m    215\u001b[0m     \u001b[0;32mif\u001b[0m \u001b[0mon_error_fn\u001b[0m \u001b[0;32mis\u001b[0m \u001b[0;32mnot\u001b[0m \u001b[0;32mNone\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    216\u001b[0m         \u001b[0mon_error_fn\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mexc\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
            "\u001b[0;32m/usr/local/lib/python3.12/dist-packages/google/api_core/retry/retry_unary.py\u001b[0m in \u001b[0;36mretry_target\u001b[0;34m(target, predicate, sleep_generator, timeout, on_error, exception_factory, **kwargs)\u001b[0m\n\u001b[1;32m    145\u001b[0m     \u001b[0;32mwhile\u001b[0m \u001b[0;32mTrue\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    146\u001b[0m         \u001b[0;32mtry\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 147\u001b[0;31m             \u001b[0mresult\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mtarget\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m    148\u001b[0m             \u001b[0;32mif\u001b[0m \u001b[0minspect\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0misawaitable\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mresult\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    149\u001b[0m                 \u001b[0mwarnings\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mwarn\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0m_ASYNC_RETRY_WARNING\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
            "\u001b[0;32m/usr/local/lib/python3.12/dist-packages/google/api_core/timeout.py\u001b[0m in \u001b[0;36mfunc_with_timeout\u001b[0;34m(*args, **kwargs)\u001b[0m\n\u001b[1;32m    128\u001b[0m                 \u001b[0mkwargs\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m\"timeout\"\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mremaining_timeout\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    129\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 130\u001b[0;31m             \u001b[0;32mreturn\u001b[0m \u001b[0mfunc\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m    131\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    132\u001b[0m         \u001b[0;32mreturn\u001b[0m \u001b[0mfunc_with_timeout\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
            "\u001b[0;32m/usr/local/lib/python3.12/dist-packages/google/api_core/grpc_helpers.py\u001b[0m in \u001b[0;36merror_remapped_callable\u001b[0;34m(*args, **kwargs)\u001b[0m\n\u001b[1;32m     73\u001b[0m     \u001b[0;32mdef\u001b[0m \u001b[0merror_remapped_callable\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     74\u001b[0m         \u001b[0;32mtry\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 75\u001b[0;31m             \u001b[0;32mreturn\u001b[0m \u001b[0mcallable_\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m     76\u001b[0m         \u001b[0;32mexcept\u001b[0m \u001b[0mgrpc\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mRpcError\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0mexc\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     77\u001b[0m             \u001b[0;32mraise\u001b[0m \u001b[0mexceptions\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mfrom_grpc_error\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mexc\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;32mfrom\u001b[0m \u001b[0mexc\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
            "\u001b[0;32m/usr/local/lib/python3.12/dist-packages/google/ai/generativelanguage_v1beta/services/generative_service/transports/rest.py\u001b[0m in \u001b[0;36m__call__\u001b[0;34m(self, request, retry, timeout, metadata)\u001b[0m\n\u001b[1;32m   1159\u001b[0m             \u001b[0;31m# subclass.\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m   1160\u001b[0m             \u001b[0;32mif\u001b[0m \u001b[0mresponse\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mstatus_code\u001b[0m \u001b[0;34m>=\u001b[0m \u001b[0;36m400\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m-> 1161\u001b[0;31m                 \u001b[0;32mraise\u001b[0m \u001b[0mcore_exceptions\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mfrom_http_response\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mresponse\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m   1162\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m   1163\u001b[0m             \u001b[0;31m# Return the response\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
            "\u001b[0;31mTooManyRequests\u001b[0m: 429 POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash-exp:generateContent?%24alt=json%3Benum-encoding%3Dint: You exceeded your current quota. Please migrate to Gemini 2.0 Flash Preview (Image Generation) (models/gemini-2.0-flash-preview-image-generation) for higher quota limits. For more information on this error, head to: https://ai.google.dev/gemini-api/docs/rate-limits."
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [],
      "metadata": {
        "id": "sUWveCszV3zl"
      },
      "execution_count": null,
      "outputs": []
    }
  ]
}